package com.ywjh.inter.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ywjh.inter.conn.DBConnection;
import com.ywjh.inter.dao.*;
import com.ywjh.inter.entity.*;
import com.ywjh.inter.utils.StrUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class PatientDataService {
	private static PatientDataService instance;
	private BloodPressureDAO bloodPressureDAO;
	private BloodGlucoseDAO bloodGlucoseDAO;
	private AlarmDataDAO alarmDataDAO;

	private CholesterolDAO cholesterolDAO;
	private UricAcidDAO uricAcidDAO;

	public static PatientDataService getInstance() {
		if (instance == null) {
			instance = new PatientDataService();
			instance.bloodPressureDAO = new BloodPressureDAO();
			instance.bloodGlucoseDAO = new BloodGlucoseDAO();
			instance.alarmDataDAO = new AlarmDataDAO();
			instance.uricAcidDAO = new UricAcidDAO();
			instance.cholesterolDAO = new CholesterolDAO();
		}
		return instance;
	}

	public boolean addBloodPressure(BloodPressureEntity bloodPressureEntity) {
		boolean b = false;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			b = bloodPressureDAO.insert(conn, bloodPressureEntity);
			if (b) {
				addAlarmBpre(conn, bloodPressureEntity);
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return b;
	}

	public boolean updateBloodPressure(BloodPressureEntity bloodPressureEntity) {
		boolean b = false;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			b = bloodPressureDAO.update(conn, bloodPressureEntity);
			if (b) {
				addAlarmBpre(conn, bloodPressureEntity);
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return b;
	}

	private void addAlarmBpre(Connection conn, BloodPressureEntity bloodPressureEntity) {
		if (bloodPressureEntity == null) {
			return;
		}

		float hi = bloodPressureEntity.getHi();
		float low = bloodPressureEntity.getLow();
		if (hi <= 0 || low <= 0) {
			return;
		}
		try {
			AlarmDataEntity alarmDataEntity = new AlarmDataEntity();
			alarmDataEntity.setAdd_time(new Timestamp(System.currentTimeMillis()));
			alarmDataEntity.setAlarm_type("bpre");
			alarmDataEntity.setData_id(bloodPressureEntity.getId());
			alarmDataEntity.setStatus(1);
			alarmDataEntity.setUser_id(bloodPressureEntity.getUser_id());
			if (hi <= 130 && low <= 85) {
				// 正常
				return;
			} else if (hi <= 139 && low <= 89) {
				alarmDataEntity.setData_type("warning");
				// 偏高
			} else if (hi <= 159 && low <= 99) {
				alarmDataEntity.setData_type("mild");
				// 轻度
			} else if (hi <= 179 && low <= 109) {
				// 中度
				alarmDataEntity.setData_type("moderate");
			} else {
				// 重度
				alarmDataEntity.setData_type("severe");
			}
			alarmDataDAO.insert(conn, alarmDataEntity);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public BloodPressureEntity findBloodPressureById(int id) {
		BloodPressureEntity e = null;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			e = bloodPressureDAO.findById(conn, id);
		} catch (ClassNotFoundException | SQLException e1) {
			e1.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return e;

	}

	private void addAlarmBgluData(Connection conn, BloodGlucoseEntity bg) throws SQLException {
		if(bg==null||bg.getPlan_id()==-1) {
			return;
		}
		Map<Integer, BGluRangeEntity> userBgluAlertMap = SettingService.getInstance().getBgluRange(bg.getUser_id());
		BGluRangeEntity gluRangeEntity = userBgluAlertMap.get(bg.getPlan_id());
		float low = 0.0f;
		float hi = 0.0f;
		if (gluRangeEntity != null) {
			String[] alert = gluRangeEntity.getWarning_range().split(";");
			low = Float.parseFloat(alert[0]);
			hi = Float.parseFloat(alert[1]);
		}
		System.out.println("plan_id:" + bg.getPlan_id() + " low:" + low + " hi:" + hi);
		AlarmDataEntity dataEntity = new AlarmDataEntity();
		if (bg.getData() > low && bg.getData() < hi) {
			System.out.println("血糖正常 返回");
			return;
		}
		if (bg.getData() <= low && low > 0) {
			dataEntity.setData_type("low");
		} else if (bg.getData() >= hi && hi > 0) {
			dataEntity.setData_type("hi");
		}
		dataEntity.setAdd_time(new Timestamp(System.currentTimeMillis()));
		dataEntity.setAlarm_type("bglu");
		dataEntity.setData_id(bg.getId());
		dataEntity.setStatus(1);
		dataEntity.setUser_id(bg.getUser_id());
		alarmDataDAO.insert(conn, dataEntity);
	}

	public boolean addBloodGlucose(BloodGlucoseEntity bg) {
		boolean b = false;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			int id = bloodGlucoseDAO.insert(conn, bg);
			if (id > -1) {// 添加报警数据
				bg.setId(id);
				addAlarmBgluData(conn, bg);
				b = true;
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return b;
	}

	public BloodGlucoseEntity findBloodGlucoseById(int id) {
		BloodGlucoseEntity e = null;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			e = bloodGlucoseDAO.findById(conn, id);
		} catch (ClassNotFoundException | SQLException e1) {
			e1.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return e;
	}

	public boolean updateBloodGlucose(BloodGlucoseEntity bg) {
		boolean b = false;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			b = bloodGlucoseDAO.update(conn, bg);
			if (b) {
				addAlarmBgluData(conn, bg);
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return b;
	}

	public Map<String, Map<Integer, List<BloodGlucoseEntity>>> findBloodGlucoseByTime(String startTime, String endTime,
			int userId) {
		Map<String, Map<Integer, List<BloodGlucoseEntity>>> map = new LinkedHashMap<String, Map<Integer, List<BloodGlucoseEntity>>>();
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			Timestamp end = StrUtil.getTimestamp(endTime);
			Timestamp start = StrUtil.getTimestamp(startTime);
			long betweenDays = (end.getTime() - start.getTime()) / (1000L * 3600L * 24L);
			JSONArray planArray = DocService.getInstance().getBGluPlan();
			for (int i = 0; i <= betweenDays; i++) {
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(end.getTime());
				cal.add(Calendar.DATE, i * -1);
				String time = StrUtil.getYYYYMMDD(cal.getTimeInMillis());
				Map<Integer, List<BloodGlucoseEntity>> planDataMap = new LinkedHashMap<>();
				for (int j = 0; j < planArray.size(); j++) {
					JSONObject pj = planArray.getJSONObject(j);
					// System.out.println("dataList q="+"uid="+userId+",time="+time+"
					// pid="+pj.getInt("id"));
					List<BloodGlucoseEntity> dataList = bloodGlucoseDAO.query(conn, userId, time, pj.getInt("id"));
					// System.out.println("dataList="+dataList.size());
					planDataMap.put(pj.getInt("id"), dataList);
				}
				map.put(time, planDataMap);
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return map;
	}

	public List<BloodGlucoseEntity> listBloodGlucoseByTime(String startTime, String endTime, int userId) {
		Connection conn = null;
		List<BloodGlucoseEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = bloodGlucoseDAO.query(conn, userId, startTime, endTime);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}

	public List<BloodPressureEntity> listBloodPressureByTime(String startTime, String endTime, int userId) {
		Connection conn = null;
		List<BloodPressureEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = bloodPressureDAO.query(conn, userId, startTime, endTime);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}

	public static String getLeadStr(String str) {
		if (str == null) {
			return "";
		}
		String first = str.substring(0, 1);
		if (isContainChinese(first)) {
			return first;
		}
		str = str.trim();
		str = str.replaceAll(" +", " ");
		String[] d = str.split(" ");
		for (String s : d) {
			System.out.println(s);
		}
		if (d.length >= 2) {
			return d[0].toUpperCase().substring(0, 1) + d[1].toUpperCase().substring(0, 1);
		} else {
			return first.toUpperCase();
		}
	}

	public static boolean isContainChinese(String str) {
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			return true;
		}
		return false;
	}

	public Map<String, List<BloodPressureEntity>> findBloodPressureByTime(String startTime, String endTime,
			int userId) {
		Map<String, List<BloodPressureEntity>> map = new LinkedHashMap<>();
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			List<BloodPressureEntity> list = bloodPressureDAO.query(conn, userId, startTime, endTime);
			for (BloodPressureEntity bloodPressureEntity : list) {
				String time=StrUtil.getYYYYMMDD(bloodPressureEntity.getCheck_time());
				if(map.get(time)==null) {
					List<BloodPressureEntity> sub=new LinkedList<>();
					sub.add(bloodPressureEntity);
					map.put(time, sub);
				}else {
					List<BloodPressureEntity> sub=map.get(time);
					sub.add(bloodPressureEntity);
				}
			}
		} catch (ClassNotFoundException |

				SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return map;
	}

	public List<AlarmDataEntity> getPatientAlarmList(int user_id, int page, int num) {
		List<AlarmDataEntity> list = null;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			list = alarmDataDAO.listByUserId(conn, user_id, page, num);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return list;
	}

	public List<AlarmDataEntity> getPatientAlarmListByDocId(int user_id, int page, int num) {
		List<AlarmDataEntity> list = null;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			String array = "";
			List<Integer> friendList = DoctorService.getInstance().getPatientIdList(user_id);
			if (friendList.isEmpty()) {
				return new LinkedList<AlarmDataEntity>();
			} else {
				for (int fid : friendList) {
					array += fid + ",";
				}
				if (array.endsWith(",")) {
					array = array.substring(0, array.length() - 1);
				}
				list = alarmDataDAO.listByUsersId(conn, array, page, num);
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return list;
	}

	public BloodGlucoseEntity findBloodBluLeastByUserId(int user_id) {
		Connection conn = null;
		BloodGlucoseEntity bloodGlucoseEntity = null;
		try {
			conn = DBConnection.getDBConnection();
			try {
				bloodGlucoseEntity = bloodGlucoseDAO.list(conn, user_id, 1).get(0);
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return bloodGlucoseEntity;
	}

	public String getAlarm(int user_d, int plan_id, float data) {
		Map<Integer, BGluRangeEntity> userBgluAlertMap = SettingService.getInstance().getBgluRange(user_d);
		BGluRangeEntity gluRangeEntity = userBgluAlertMap.get(plan_id);
		float low = 0.0f;
		float hi = 0.0f;
		if (gluRangeEntity != null) {
			String[] alert = gluRangeEntity.getWarning_range().split(";");
			low = Float.parseFloat(alert[0]);
			hi = Float.parseFloat(alert[1]);
		}
		if (data <= low && low > 0) {
			return "low";
		} else if (data >= hi && hi > 0) {
			return "hi";
		} else {
			return "ok";
		}
	}

	public List<BloodGlucoseEntity> listBloodGlucoseByTime(String startTime, String endTime, String users) {
		Connection conn = null;
		List<BloodGlucoseEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = bloodGlucoseDAO.query(conn, users, startTime, endTime);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}

	public List<BloodGlucoseEntity> listBloodGlucoseByAllTime( String users) {
		Connection conn = null;
		List<BloodGlucoseEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = bloodGlucoseDAO.query(conn, users);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}

	public List<BloodPressureEntity> listBloodPressureByTime(String startTime, String endTime, String users) {
		Connection conn = null;
		List<BloodPressureEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = bloodPressureDAO.query(conn, users, startTime, endTime);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}

	public List<BloodPressureEntity> listBloodPressureByAllTime( String users) {
		Connection conn = null;
		List<BloodPressureEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = bloodPressureDAO.query(conn, users);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}

	public int is_check_today(int user_id) {
		boolean b = false;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			String today = StrUtil.getYYYYMMDD(new Timestamp(System.currentTimeMillis()));
			List<BloodGlucoseEntity> list = bloodGlucoseDAO.query(conn, user_id, today, today);
			if (!list.isEmpty()) {
				b = true;
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		//调整客户端，更改为显示当天有数据
		//return b ? 1 : 0;
		return b ? 0 : 1;
	}

	public int is_7d_no_check(int user_id) {
		boolean b = false;

		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			String today = StrUtil.getYYYYMMDD(new Timestamp(System.currentTimeMillis()));
			String start = StrUtil.getYYYYMMDD(new Timestamp(System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000)));
			List<BloodGlucoseEntity> list = bloodGlucoseDAO.query(conn, user_id, start, today);
			if (list.isEmpty()) {
				b = true;
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		//调整客户端，更改为显示7天有数据
		// return b ? 1 : 0;
		return b ? 0 : 1;
	}

	public int is_7d_alarm(int user_id) {
		boolean b = false;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			String today = StrUtil.getYYYYMMDD(new Timestamp(System.currentTimeMillis()));
			String start = StrUtil.getYYYYMMDD(new Timestamp(System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000)));
			List<BloodGlucoseEntity> list = bloodGlucoseDAO.query(conn, user_id, start, today);
			Map<Integer, BGluRangeEntity> userBgluAlertMap = SettingService.getInstance().getBgluRange(user_id);
			for (BloodGlucoseEntity entity : list) {
				BGluRangeEntity gluRangeEntity = userBgluAlertMap.get(entity.getPlan_id());
				float low = 0.0f;
				float hi = 0.0f;
				if (gluRangeEntity != null) {
					String[] alert = gluRangeEntity.getWarning_range().split(";");
					low = Float.parseFloat(alert[0]);
					hi = Float.parseFloat(alert[1]);
				}
				JSONObject bgluJson = new JSONObject();
				bgluJson.put("id", entity.getId());
				bgluJson.put("data", entity.getData());
				bgluJson.put("check_time", StrUtil.getYYYYMMDDHHMISS(entity.getCheck_time()));
				bgluJson.put("memo", entity.getMemo());
				if (entity.getData() <= low && low > 0) {
					b = true;
					break;
				} else if (entity.getData() >= hi && hi > 0) {
					b = true;
					break;
				}
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return b ? 1 : 0;
	}

	public boolean addCholesterol(CholesterolEntity entity) {
		boolean b = false;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			int id = cholesterolDAO.insert(conn, entity);
			if(id>0){
				b=true;
			}

		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return b;
	}

	public boolean addUricAcid(UricAcidEntity entity) {
		boolean b = false;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			int id = uricAcidDAO.insert(conn, entity);
			if(id>0){
				b=true;
			}

		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return b;
	}

	public List<CholesterolEntity> ListCholesterolByTime(int userid, String startTime, String endTime){
		Connection conn = null;
		List<CholesterolEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = cholesterolDAO.query(conn, userid,startTime,endTime);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}
	
	public List<CholesterolEntity> ListCholesterolByTime(String users, String startTime, String endTime){
		Connection conn = null;
		List<CholesterolEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = cholesterolDAO.query(conn, users, startTime,endTime);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}

	public List<UricAcidEntity> ListUricAcidByTime(int userid, String startTime, String endTime){
		Connection conn = null;
		List<UricAcidEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = uricAcidDAO.query(conn, userid,startTime,endTime);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}
	
	public List<UricAcidEntity> ListUricAcidByTime(String users, String startTime, String endTime) {
		Connection conn = null;
		List<UricAcidEntity> dataList = null;
		try {
			conn = DBConnection.getDBConnection();
			dataList = uricAcidDAO.query(conn, users, startTime,endTime);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return dataList;
	}

}
